<template>
  <PanelHead :route="route"/>
  <div class="btns">
    <el-button :icon="Plus" @click="dialogFormVisible = true" size="small">新增</el-button>
  </div>
  <el-table :data="tableData.list">
    <el-table-column label="ID" prop="id" />
    <el-table-column label="昵称" prop="name" />
    <el-table-column label="菜单权限" prop="permissionName" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button @click="open(scope.row)" type="primary">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="pagination-info">
    <el-pagination
    v-model:current-page="paginationData.pageNum"
    :background="false"
    layout="total, prev, pager, next"
    :page-size="paginationData.pageSize"
    :total="tableData.total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    size="small"/>
  </div>
  <el-dialog v-model="dialogFormVisible" :beforeClose="beforeClose" title="添加权限">
    <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
    <el-form-item v-show="false" label="id" prop="id">
        <el-input v-model="form.id" placeholder="ID" />
  </el-form-item>
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item label="权限" prop="permision">
        <el-tree :data="permissionData" style="max-width: 600px;" node-key="id" show-checkbox
          :default-checked-keys="defaultKeys" ref="treeRef"
          :default-expanded-keys="[2]">
        </el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="confirm(formRef)">确定</el-button>
    </template>

  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted,nextTick } from 'vue'
import { userGetMenu ,userSetMenu ,menuList} from '../../api'
import { ElMessage } from 'element-plus'
import PanelHead from '../../components/panelHead.vue'
import { Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const route = useRoute()

const handleSizeChange = (val) => {
  paginationData.pageSize = val
  getListData()
}

const handleCurrentChange = (val) => {
  paginationData.pageNum = val
  getListData()
}

onMounted(() => {
  userGetMenu().then((res) => {
    console.log(res.data)
    if (res.data.code === 10000) {
      permissionData.value = res.data.data
    } else {
      ElMessage.error('获取权限数据失败')
    }
  }).catch((error) => {
    console.error('获取权限数据异常:', error)
    ElMessage.error('获取权限数据异常')
  })
  getListData()
})

//列表数据
const tableData = reactive({
  list: [],
  total: 0
})


//列表数据
const getListData = () => {
  menuList(paginationData).then(({ data }) => {
    const {list , total} = data.data
    tableData.list = list
    tableData.total = total
    console.log(data.data.list.permissions, 'menu list data')
  })
}


const paginationData = reactive({
  pageNum: 1,
  pageSize: 10,
});



const open = (rowData = {}) => {
  dialogFormVisible.value = true
  nextTick(() => {
    if(rowData && Object.keys(rowData).length > 0){
      // 编辑模式：设置当前行的数据
      Object.assign(form, {id:rowData.id,name: rowData.name})
      // 使用正确的字段名 permission 而不是 permissions
      // 确保传入的是数组，如果不是则传入空数组
      treeRef.value.setCheckedKeys(Array.isArray(rowData.permission) ? rowData.permission : [])
    } else {
      // 新增模式：清空表单并设置默认选中项
      form.id = ''
      form.name = ''
      // 设置默认选中项
      treeRef.value.setCheckedKeys(defaultKeys)
    }
  })
}


const defaultKeys = [4, 5]

const permissionData = ref([])

const form = reactive({
  name: '',
  permissions: '',
})

const dialogFormVisible = ref(false)

const beforeClose = () => {
  dialogFormVisible.value = false
  //重置表单
  formRef.value.resetFields()
  treeRef.value.setCheckedKeys([defaultKeys])
}

const treeRef = ref()
const formRef = ref()

const confirm = async () => {
  await formRef.value.validate((valid) => {
    if (!valid) return
    if (valid) {
      const permissions = JSON.stringify(treeRef.value.getCheckedKeys())
      userSetMenu({ name: form.name, permissions ,id: form.id}).then((res) => {
          if (res.data.code === 10000) {
            ElMessage.success('添加成功')
          } else {
            ElMessage.error('添加失败')
          console.log(form.name.toString())
          console.log(permissions)
          console.log(form.id)
        }
        beforeClose()
        getListData()
      })
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入权限名称',
      trigger: 'blur'
    },
  ],
})
</script>

<style scoped>
.group-container {
  padding: 20px;
}
.btns {
  margin: 15px 0;
}
</style>
